# coding: utf-8

import config
import app.tools as tool
from PyQt4.QtCore import Qt
from PyQt4 import QtCore
from app.ui import Tab, Tree, Icon
from app.ui.dialog import Dialog
from app.ui.client import ClientWidget
from app.ui.cluster import ClusterWidget
from app.tools.menu import Menu
from app.tools.dialog import MessageBox
from app.tools.window import *
from lib.tools.logger import Logger
from lib.tools.type import TreeItemType
from app.tools.splitter import Splitter
from app.connect import ConnectWindow


class MainWindow(QtGui.QMainWindow):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.logger = Logger(self)
        self.icon = Icon()
        self.init_ui()
        self.init_style()

    def init_style(self):
        style = QtCore.QString(open(config.RESOURCE_STYLE_SHEET).read())
        self.setStyleSheet(style)

    def init_ui(self):
        self.setEnabled(True)
        self.setObjectName(tool._from_utf8("MainWindow"))
        self.setWindowTitle(tool._translate("MainWindow", config.MAIN_WINDOW_TITLE, None))
        desktop_geometry = get_screen_geometry()
        # desktop_geometry = QtCore.QRect(0, 0, 800, 600)
        desktop_width = desktop_geometry.width()
        desktop_height = desktop_geometry.height()
        window_height = desktop_height * config.MAIN_WINDOW_RATIO
        window_width = desktop_width * (window_height / desktop_height)
        center_left = (desktop_width - window_width) / 2
        center_top = (desktop_height - window_height) / 2
        current_rect = QtCore.QRect(center_left, center_top, window_width, window_height)
        print('main:', current_rect)
        self.setGeometry(current_rect)
        # self.setMinimumSize(QtCore.QSize(window_width, window_height))
        # self.setMaximumSize(QtCore.QSize(window_width, window_height))
        self.setWindowIcon(self.icon.get(config.ICON_LOGO))

        self.vertical_layout_widget_left = QtGui.QWidget(self)
        self.vertical_layout_widget_left.setGeometry(QtCore.QRect(0, 0, 270, 761))
        self.vertical_layout_widget_left.setObjectName(tool._from_utf8("vertical_layout_widget_left"))

        self.left_vertical_layout = QtGui.QVBoxLayout(self.vertical_layout_widget_left)
        self.left_vertical_layout.setSizeConstraint(QtGui.QLayout.SetDefaultConstraint)

        self.tree = Tree(self)
        self.tree_widget = self.tree.get_instance()
        self.tree_widget.on_clicked(self.tree_clicked)
        self.left_vertical_layout.addWidget(self.tree_widget, QtCore.Qt.AlignHCenter | QtCore.Qt.AlignVCenter)


        self.left_bottom_horizontal_layout = QtGui.QHBoxLayout()

        self.connect_button = QtGui.QPushButton(self.vertical_layout_widget_left)
        self.connect_button.setIcon(self.icon.get(config.ICON_ADD))
        self.connect_button.setText(tool._from_utf8('Connect'))
        self.connect_button.clicked.connect(self.connect_clicked)
        self.left_bottom_horizontal_layout.addWidget(self.connect_button)

        self.connect_client_button = QtGui.QPushButton(self.vertical_layout_widget_left)
        self.connect_client_button.setIcon(self.icon.get(config.ICON_ADD))
        self.connect_client_button.setText(tool._from_utf8('Client'))
        self.connect_client_button.clicked.connect(self.connect_client_clicked)
        self.left_bottom_horizontal_layout.addWidget(self.connect_client_button)

        self.connect_cluster_button = QtGui.QPushButton(self.vertical_layout_widget_left)
        self.connect_cluster_button.setIcon(self.icon.get(config.ICON_ADD))
        self.connect_cluster_button.setText(tool._from_utf8('Cluster'))
        self.connect_cluster_button.clicked.connect(self.connect_cluster_clicked)
        self.left_bottom_horizontal_layout.addWidget(self.connect_cluster_button)

        self.left_vertical_layout.addLayout(self.left_bottom_horizontal_layout)

        self.vertical_layout_widget_right_top = QtGui.QWidget(self)

        self.tab = Tab(self)
        self.tab.set_current_index()
        self.tab_widget = self.tab.get_instance()
        tab_width = window_width * 0.8
        tab_height = window_height * 0.8
        tab_size = QtCore.QSize(tab_width, tab_height)
        self.tab_widget.setMinimumSize(QtCore.QSize(690, 550))
        self.tab_widget.resize(tab_size)
        # self.tab_widget.resize(self.size())
        self.right_vertical_layout = QtGui.QVBoxLayout(self.vertical_layout_widget_right_top)
        self.right_vertical_layout.addWidget(self.tab_widget)

        self.vertical_layout_widget_right_bottom = QtGui.QWidget(self)

        self.log_browser = QtGui.QTextBrowser(self.vertical_layout_widget_right_bottom)
        self.log_browser.setObjectName(tool._from_utf8("log_browser"))

        self.log_label = QtGui.QLabel(self.vertical_layout_widget_right_bottom)
        self.log_label.setAlignment(Qt.AlignLeft)
        # self.log_label.setScaledContents(True)
        self.log_label.resize(self.size())
        log_pixmap = self.icon.get_pixmap(config.ICON_LOG)
        log_pixmap = log_pixmap.scaled(20, 20, aspectRatioMode=Qt.KeepAspectRatio)
        self.log_label.setPixmap(log_pixmap)

        self.vertical_layout = QtGui.QVBoxLayout(self.vertical_layout_widget_right_bottom)
        self.vertical_layout.setObjectName(tool._from_utf8("vertical_layout"))
        self.vertical_layout.addWidget(self.log_label)
        self.vertical_layout.addWidget(self.log_browser)

        self.right_splitter = Splitter(self)
        # self.right_splitter.hide()
        self.right_splitter.setHandleWidth(1)
        self.right_splitter.setStretchFactor(0, 8)
        self.right_splitter.setStretchFactor(1, 2)
        self.right_splitter.addWidget(self.vertical_layout_widget_right_top)
        self.right_splitter.addWidget(self.vertical_layout_widget_right_bottom)
        self.right_splitter.setOrientation(Qt.Vertical)

        self.main_splitter = Splitter(self)
        self.main_splitter.setHandleWidth(1)
        self.main_splitter.setStretchFactor(0, 2)
        self.main_splitter.setStretchFactor(1, 8)
        self.main_splitter.addWidget(self.vertical_layout_widget_left)
        self.main_splitter.addWidget(self.right_splitter)
        self.main_splitter.setAutoFillBackground(True)
        self.main_splitter.setOrientation(Qt.Horizontal)
        self.setCentralWidget(self.main_splitter)

        Menu.init(self)

        QtCore.QMetaObject.connectSlotsByName(self)

    def tree_clicked(self, item, _):
        value = item.value
        type = value['type']
        if type == TreeItemType.Key:
            name = value['name']
            parent = item.parent()
            factory = parent.value['factory']
            if self.right_splitter.isHidden():
                self.right_splitter.show()
            self.tab.add(item, factory, name)

    def connect_clicked(self):
        self.connect_window = ConnectWindow(self)
        # self.connect_window.display(0)
        # self.connect_window.set_client_data({'id': 1, 'name': 'test', 'auth': '123456@', 'node': ('localhost', 6379)})
        # self.connect_window.set_cluster_data({'id': 1, 'name': 'test', 'auth': '123456@', 'nodes': [
        #     ('10.168.2.39', 7000),
        #     ('10.168.2.39', 7001),
        #     ('10.168.2.39', 7002),
        # ]})
        self.connect_window.show()

    def connect_client_clicked(self):
        print('connect_client_clicked')
        self.client_dialog = Dialog(self, 'Connect Client')
        self.client_dialog.set_window_size(0.5)
        self.client_window = ClientWidget(self, self.client_dialog)
        self.client_window.set_data({'id': 1, 'name': 'test', 'auth': '123456@', 'node': ('localhost', 6379)})
        self.client_dialog.show()

    def connect_cluster_clicked(self):
        print('connect_cluster_clicked')
        self.cluster_dialog = Dialog(self, 'Connect Cluster')
        self.cluster_dialog.set_window_size(0.8)
        self.cluster_window = ClusterWidget(self, self.cluster_dialog)
        self.cluster_window.set_data({'id': 1, 'name': 'test', 'auth': '123456@', 'nodes': [
            ('10.168.2.39', 7000),
            ('10.168.2.39', 7001),
            ('10.168.2.39', 7002),
        ]})
        self.cluster_dialog.show()

    def log(self, message):
        self.log_browser.append(str(message))

    def __resize(self, window_size):
        tree_width = self.tree_widget.width()
        window_width, window_height = window_size.width(), window_size.height()
        tab_width = window_width - tree_width - 35
        # tab_width = self.log_browser.width()
        log_height = self.vertical_layout_widget_right_bottom.height()
        tab_height = window_height - log_height
        # print('window: %d, %d' % (window_width, window_height))
        # print('excess: %d, %d' % (tree_width, log_height))
        # print('tab: %d, %d' % (tab_width, tab_height))
        tab_size = QtCore.QSize(tab_width, tab_height)
        Logger.get_instance().info(tab_size)
        self.tab.resize(tab_size)


    def resizeEvent(self, event):
        self.__resize(event.size())

    def changeEvent(self, event):
        if event.type() != QtCore.QEvent.WindowStateChange:
            return
        if self.windowState() == Qt.WindowMaximized:
            # self.showMaximized()
            desktop_geometry = get_available_geometry()
            desktop_width = desktop_geometry.width()
            desktop_height = desktop_geometry.height()
            window_size = QtCore.QSize(desktop_width, desktop_height)
            # print(window_size)
            # self.resize(window_size)
            self.__resize(window_size)
        else:
            self.__resize(self.size())

    def closeEvent(self, event):
        reply = MessageBox.confirm(self, 'tips', 'Whether or not to quit?')
        func = event.accept if reply == QtGui.QMessageBox.Yes else event.ignore
        func()
